package com.emenu;

import java.util.ArrayList;
import java.util.List;

import com.emenu.SurePost.sendTask;
import com.emenu.application.StaticObject;
import com.emenu.bean.BusHitDetail;
import com.emenu.bean.BusHitMaster;
import com.emenu.bean.PubPrinter;
import com.emenu.bean.PubPrinterTable;
import com.emenu.bean.PubTable;
import com.emenu.common.CM;
import com.emenu.common.Common;
import com.emenu.common.GetWebServiceData;
import com.emenu.common.JsonUntil;
import com.emenu.common.NetUntil;
import com.emenu.common.PostWebServiceData;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class FunhitFragment extends Fragment {

	public EditText hittab;
	public TextView hittabname;
	public EditText funprint;
	public Button chooseprint;
	public Button print;
	ListView listView1;
	ListView listView2;
	public ProgressBar Pro1;
	public ProgressBar Pro2;

	public StaticObject SO;
	Context cn;
	public static final String SET_NAME = "jpSetFile";
	private String url;

	List<BusHitMaster> list = new ArrayList<BusHitMaster>();
	List<BusHitDetail> list2 = new ArrayList<BusHitDetail>();
	List<PubPrinter> PubPrinterlist = new ArrayList<PubPrinter>();
	List<PubPrinterTable> PubPrinterTablelist = new ArrayList<PubPrinterTable>();
	private String printcode = "";
	//选中的主表code
	String mascode;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		SO = (StaticObject) activity.getApplication();
		PubPrinterlist = SO.getPubPrinterList();
		PubPrinterTablelist = SO.getPubPrinterTableList();
		cn = this.getActivity();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.funhit, container, false);

		findViewsById(v);
		funprint.setText("默认打印机");

		setListener();
		SharedPreferences settings = cn.getSharedPreferences(SET_NAME, 0);
		url = settings.getString("url", "");
		return v;
	}

	/** 视图 样式 */
	private void findViewsById(View v) {
		hittab = (EditText) v.findViewById((R.id.fun_hittab));
		hittabname = (TextView) v.findViewById((R.id.fun_hittabname));
		funprint = (EditText) v.findViewById((R.id.fun_print));
		chooseprint = (Button) v.findViewById((R.id.funchooseprint));
		print = (Button) v.findViewById((R.id.hitprint));
		listView1 = (ListView) v.findViewById(R.id.hitlistView1);
		listView2 = (ListView) v.findViewById(R.id.hitlistView2);

		Pro1 = (ProgressBar) v.findViewById(R.id.progressBar1);
		Pro2 = (ProgressBar) v.findViewById(R.id.progressBar2);
		// 设置进度条是否自动运转，即设置其不确定模式，false表是不自动运转

		Pro1.setIndeterminate(false);
		Pro2.setIndeterminate(false);

	}

	/** 设置监听器 */
	private void setListener() {
		hittab.addTextChangedListener(txwatcher);
		listView1.setOnItemClickListener(listview1listener);
		chooseprint.setOnClickListener(chooseListener);
		print.setOnClickListener(printListener);

	}

	private TextWatcher txwatcher = new TextWatcher() {
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void afterTextChanged(Editable s) {

			Pro1.setVisibility(View.VISIBLE);

			if (NetUntil.isConnect( cn)) {
				for (PubTable pt : SO.getPubTableList()) {
					if ((hittab.getText() + "").equals(pt.getHelpcode())) {
						hittabname.setText(pt.getName());
						// 台号异步取点菜主表数据
						new getMasTask().execute(pt.getCode());
						Listview1Adapter adapter = new Listview1Adapter();
						listView1.setAdapter(adapter);
						// 默认打印机
						for (PubPrinterTable prt : PubPrinterTablelist) {
							if (pt.getCode().equals(prt.getTable_code())) {
								printcode = prt.getPrint_code();
								funprint.setText(prt.getPrintdesc());
								break;
							}

						}
						break;
					}

				}

			} else {
				Common.alertalam(cn, "网络出错", "网络出错！请关闭后再次发送！");
			}

			Pro1.setVisibility(View.GONE);

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

	};

	private OnItemClickListener listview1listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// 选中的点菜主表code
			  mascode = list.get(arg2).getCode();
			// list2 = null;

			Pro2.setVisibility(View.VISIBLE);
			// 异步取菜明细表数据
			new getMasDetailTask().execute(mascode);

			Listview2Adapter adapter2 = new Listview2Adapter();
			listView2.setAdapter(adapter2);
			Pro2.setVisibility(View.GONE);

		}

	};

	private OnClickListener chooseListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			//  
			int size1 = PubPrinterlist.size();

			String[] sArray = new String[size1];

			for (int i = 0; i < PubPrinterlist.size(); i++) {

				sArray[i] = (String) PubPrinterlist.get(i).getPrintdesc();

			}

			final String[] sArraytemp = sArray;

			AlertDialog.Builder builder = new AlertDialog.Builder(
					((Activity) cn).getParent());

			builder.setTitle("请选择打印机:");

			builder.setItems(sArray,

			new android.content.DialogInterface.OnClickListener() {

				public void onItemSelected(AdapterView<?> parent,

				View view, int position, long id) {

					// String str = Integer.toString(position);//
					  printcode = PubPrinterlist.get(position).getCode();

				}

				public void onNothingSelected(AdapterView<?> parent) {

					// TODO Auto-generated method stub
				}

				public void onClick(DialogInterface arg0, int arg1) {

					funprint.setText(sArraytemp[arg1]);
				};

			});
			// AlertDialog alert = builder.create();
			// alert.show();
			builder.show();

		}
	};

	private OnClickListener printListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// 异步调打weservice印接口

			if (NetUntil.isConnect(cn)) {
				Log.d("111111mascode", printcode);
				Log.d("11111printcode", printcode);
				
				// 异步发送webservice
				new PostPrintTask().execute((Void) null);

			} else {
				Common.alertalam(cn, "网络出错", "网络出错！请关闭后再次发送！");
			}

		}

	};

	public class Listview1Adapter extends BaseAdapter {

		@Override
		public int getCount() {

			return list.size();
		}

		@Override
		public Object getItem(int position) {

			return list.get(position);
		}

		@Override
		public long getItemId(int position) {

			return position;

		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = ((FunMainActivity) cn).getLayoutInflater()
						.inflate(R.layout.hitmaslist, null);
			}

			TextView mashitcode;
			TextView mashittype;
			TextView mascreatetime;
			TextView mascreateusername;

			mashitcode = (TextView) convertView.findViewById(R.id.mashitcode);
			mashittype = (TextView) convertView.findViewById(R.id.mashittype);
			mascreatetime = (TextView) convertView
					.findViewById(R.id.mascreatetime);
			mascreateusername = (TextView) convertView
					.findViewById(R.id.mascreateusername);

			mashitcode.setText(list.get(position).getCode());
			mashittype.setText(list.get(position).getHit_typeName());

			mascreatetime.setText(list.get(position).getCreatedatetime());
			mascreateusername.setText(list.get(position).getCreateuserName());

			return convertView;
		}

	}

	public class Listview2Adapter extends BaseAdapter {

		@Override
		public int getCount() {
			return list2.size();

		}

		@Override
		public Object getItem(int position) {

			return list2.get(position);
		}

		@Override
		public long getItemId(int position) {

			return position;

		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = ((FunMainActivity) cn).getLayoutInflater()
						.inflate(R.layout.hitmasdtlist, null);
			}

			TextView mdmenu_code;
			TextView mdmenu_name;
			TextView mdrljtypename;
			TextView mdprice;
			TextView mdamount;
			TextView mdamount_sum;

			mdmenu_code = (TextView) convertView.findViewById(R.id.mdmenu_code);
			mdmenu_name = (TextView) convertView.findViewById(R.id.mdmenu_name);
			mdrljtypename = (TextView) convertView
					.findViewById(R.id.mdrljtypename);
			mdprice = (TextView) convertView.findViewById(R.id.mdprice);
			mdamount = (TextView) convertView.findViewById(R.id.mdamount);
			mdamount_sum = (TextView) convertView
					.findViewById(R.id.mdamount_sum);

			mdmenu_code.setText(list2.get(position).getMenucode());
			mdmenu_name.setText(list2.get(position).getMenuname());
			mdrljtypename.setText(list2.get(position).getRljtypeName());
			mdprice.setText(list2.get(position).getPrice() + "");
			mdamount.setText(list2.get(position).getAmount() + "");
			mdamount_sum.setText(list2.get(position).getAmount_sum() + "");

			return convertView;
		}

	}

	/**
	 * 异步得到bus_hit_master
	 */
	public class getMasTask extends AsyncTask<String, Void, Boolean> {

		// 执行onPreExecute()完后立即调用
		@Override
		protected Boolean doInBackground(String... params) {

			try {
				// 参数下载
				String masjson = GetWebServiceData
						.WSJson(url,
								"SELECT  a.code, a.hitcode, "
										+ "(CASE a.hit_type WHEN 0 THEN '正常' WHEN 1 THEN '加单' "
										+ "WHEN 2 THEN '赠品'  WHEN 3 THEN '退菜' ELSE '套餐' END)"
										+ " AS hit_typename, a.amount  , CONVERT(char(12) , "
										+ "a.createdatetime,108 ) createdatetime , b.name  "
										+ " FROM bus_hit_master a,Sys_user b WHERE "
										+ "a.createuser = b.code and a.table_code='"
										+ params[0] + "'  and "
										+ " a.consume_date='" + CM.formatDate()
										+ "'").replaceAll("\\\\", "\\\\\\\\");

				list = JsonUntil.getBusHitMasterList(masjson);
				return true;
			} catch (Exception e) {
				e.printStackTrace();

			}
			return false;
		}

		// doInBackground后执行
		// result 的得自于doInBackgroun
		@Override
		protected void onPostExecute(Boolean result) {

			if (!result) {
				Common.alertFinish(cn, "数据下载失败");
			}
		}

	}

	/**
	 * 异步得到BusHitDetail
	 */
	public class getMasDetailTask extends AsyncTask<String, Void, Boolean> {

		// 执行onPreExecute()完后立即调用
		@Override
		protected Boolean doInBackground(String... params) {

			try {
				// 参数下载
				String masDjson = GetWebServiceData
						.WSJson(url,
								"select a.menu_code,a.menu_name,a.price,a.amount,a.amount_sum,"
										+ "a.menutype,a.rljtype,"
										+ "(CASE a.rljtype WHEN 0 THEN '热菜' WHEN 1 THEN '冷菜' WHEN 2 THEN '酒水'   ELSE '其他' END) "
										+ " AS rljtypename  "
										+ " from bus_hit_detail a,bus_hit_master b where a.hit_code=b.code  "
										+ "  and b.code='" + params[0] + "'")
						.replaceAll("\\\\", "\\\\\\\\");

				list2 = JsonUntil.getBusHitDetailList(masDjson);

				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return false;
		}

		// doInBackground后执行
		// result 的得自于doInBackgroun
		@Override
		protected void onPostExecute(Boolean result) {

			if (!result) {
				Common.alertFinish(cn, "数据下载失败");
			}
		}

	}

	/**
	 * 异步调用打印接口
	 */
	public class PostPrintTask extends AsyncTask<Void, Void, Boolean> {

		// 执行onPreExecute()完后立即调用
		@Override
		protected Boolean doInBackground(Void... params) {

			try {
				// 参数下载

				String temps = PostWebServiceData.PostHitPrint(url, mascode, printcode,
						SO.getStaticUserName());
				Log.d("222temps", temps);

				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return false;
		}

		// doInBackground后执行
		// result 的得自于doInBackgroun
		@Override
		protected void onPostExecute(Boolean result) {

			if (!result) {
				Common.alertalam(cn, "打印失败", "打印失败，请重新打印！");
			} else {
				Common.alertalam(cn, "打印成功", "打印成功！");
			}

		}
	}
}
